package com.example.fanyi.data

import android.content.Context
import android.util.Log
import com.example.fanyi.api.YoudaoApi
import com.example.fanyi.api.YoudaoUtils
import kotlinx.coroutines.flow.Flow

class TranslationRepository(context: Context) {
    private val database = TranslationDatabase.getDatabase(context)
    private val translationDao = database.translationDao()
    private val youdaoApi = YoudaoApi.create()

    suspend fun translate(text: String, isChineseToUyghur: Boolean): TranslationResult {
        try {
            val salt = YoudaoUtils.generateSalt()
            val curtime = YoudaoUtils.getCurrentTime()
            val sign = YoudaoUtils.generateSign(text, salt, curtime)

            val from = if (isChineseToUyghur) "zh-CHS" else "ug"
            val to = if (isChineseToUyghur) "ug" else "zh-CHS"

            Log.d("Translation", "Request parameters:")
            Log.d("Translation", "Text: $text")
            Log.d("Translation", "From: $from, To: $to")
            Log.d("Translation", "Salt: $salt")
            Log.d("Translation", "Curtime: $curtime")
            Log.d("Translation", "Sign: $sign")

            val response = youdaoApi.translate(
                text = text,
                from = from,
                to = to,
                salt = salt,
                sign = sign,
                signType = "v3",
                curtime = curtime
            )

            Log.d("Translation", "Response: $response")

            return if (response.errorCode == "0") {
                val translatedText = response.translation.firstOrNull() ?: ""
                TranslationResult.Success(translatedText)
            } else {
                Log.e("Translation", "Error code: ${response.errorCode}")
                TranslationResult.Error(response.errorCode.toIntOrNull() ?: -1)
            }
        } catch (e: Exception) {
            Log.e("Translation", "Translation failed", e)
            return TranslationResult.Error(-1, e.message)
        }
    }

    fun getAllRecords(): Flow<List<TranslationRecord>> {
        return translationDao.getAllRecords()
    }

    suspend fun insertRecord(record: TranslationRecord) {
        translationDao.insert(record)
    }

    suspend fun deleteRecords(records: Set<TranslationRecord>) {
        translationDao.deleteMultiple(records.toList())
    }
}

sealed class TranslationResult {
    data class Success(val translatedText: String) : TranslationResult()
    data class Error(val code: Int, val message: String? = null) : TranslationResult()
} 